package com.csgc.camera.biz.other


import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.bean.UserInfo
import com.csgc.camera.biz.other.activity.WebViewActivity
import com.csgc.camera.constants.Constants
import com.csgc.camera.events.LoginEvents
import com.csgc.camera.events.WXAuthCodeEvents
import com.csgc.camera.http.viewmodel.AppViewModel
import com.csgc.camera.util.WXWrapper
import com.csgc.camera.util.clickWithTrigger
import com.csgc.camera.widget.dialog.LoadingPop
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityLoginBinding
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.drake.spannable.addSpan
import com.drake.spannable.movement.ClickableMovementMethod
import com.drake.spannable.span.HighlightSpan
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hlyj.http.base.tool.lib_hlyj_base.bean.BaseResult
import com.hlyj.http.base.tool.lib_hlyj_base.camera.LoginBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.LoginResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.ApiCallback
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.utils.MMKVUtils
import com.ok.common.api.GlobalApi
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi

class LoginActivity:BaseBindingActivity<ActivityLoginBinding>(ActivityLoginBinding::inflate) {

    companion object{
        fun launch(context: Context){
            context.startActivity(Intent(context,LoginActivity::class.java))
        }
    }
    private val viewModel:AppViewModel by viewModels()
    private val privacyColor: Int by lazy {
        ContextCompat.getColor(this, R.color.color_00CDC0)
    }
    private var isAgreePrivacy = false
    private val userJsonAdapter: JsonAdapter<UserInfo> by lazy{
        val moshi = Moshi.Builder().build()
        val jsonAdapter =  moshi.adapter(UserInfo::class.java)
        jsonAdapter
    }
    private val loadingPop:LoadingPop by lazy {
        LoadingPop(this,true)
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        immersionBar {
            transparentStatusBar()
            fitsSystemWindows(false)
        }
        initView()
        initData()
        initListener()

        receiveEvent<WXAuthCodeEvents> {
            val code = it.code
            val openId = it.openId
            //请求接口
            if (code.isNotEmpty()){
                loadingPop.showLoading(false)
               // viewModel.loginByWx(WxLoginParams(code,UserPreference.instance.getOaid(),packageName,AppUtil.getChannel()))
                loginByCode(LoginBean("","",openId, BaseModuleSpUtils.getInstance().getString(com.hlyj.http.base.tool.lib_hlyj_base.Constants.OAID)))
            }
        }
    }

    private fun initView(){
        binding.tvAppPrivacyTxt.text = "我已同意平台"
            .addSpan("《用户服务协议》", listOf(HighlightSpan(color = privacyColor,onClick = {
                WebViewActivity.launch(this,"用户服务协议", Constants.PrivacyUrl.protocol.url)
            })))
            .addSpan("和")
            .addSpan("《隐私政策》", listOf(HighlightSpan(color = privacyColor,onClick = {
                WebViewActivity.launch(this,"隐私政策",Constants.PrivacyUrl.privacy.url)
            })))
        binding.tvAppPrivacyTxt.movementMethod = ClickableMovementMethod()
    }

    private fun initListener(){

        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.tvLogin.clickWithTrigger {
            if (!isAgreePrivacy){
                ToastUtils.show("请同意隐私协议")
                return@clickWithTrigger
            }

            val phoneNum = binding.etPhoneNum.text.toString().trim()
            if (phoneNum.isEmpty()){
                ToastUtils.show("请输入手机号")
                return@clickWithTrigger
            }
            if (phoneNum.length != 11 || !phoneNum.startsWith("1")){
                ToastUtils.show("请输入正确手机号")
                return@clickWithTrigger
            }
//            val code = binding.etCodeNumber.text.toString().trim()
//            if (code.isEmpty()){
//                ToastUtils.show("请输入验证码")
//                return@clickWithTrigger
//            }
            //val params = CodeLoginParams(phoneNum,code,  UserPreference.instance.getOaid(),packageName,AppUtil.getChannel())
            //viewModel.loginByCode(params)
           // loginByCode(LoginBean(phoneNum,code,"",BaseModuleSpUtils.getInstance().getString(com.hlyj.http.base.tool.lib_hlyj_base.Constants.OAID)))
            sendSmsCode(phoneNum)
            CodeInputActivity.launch(this,phoneNum)
        }


        binding.etPhoneNum.addTextChangedListener { text: Editable? ->
            text?.let {
                if (binding.cvLoginCountdown.currentSecond == 0){
                    binding.cvLoginCountdown.isEnabled = it.toString().isNotEmpty()
                }
            }
        }

        binding.cvLoginCountdown.clickWithTrigger {
            val phoneNum = binding.etPhoneNum.text.toString().trim()
            if (phoneNum.isEmpty()){
                ToastUtils.show("请输入手机号")
                return@clickWithTrigger
            }
            if (phoneNum.length != 11 || !phoneNum.startsWith("1")){
                ToastUtils.show("请输入正确手机号")
                return@clickWithTrigger
            }
            //调用接口获取验证码
            //viewModel.sendSmsCode(SendCodeParams(phoneNum,packageName))
             sendSmsCode(phoneNum)
            //binding.cvLoginCountdown.start()

        }


        binding.ivPrivacyAgree.clickWithTrigger {
            isAgreePrivacy = !isAgreePrivacy
            if (isAgreePrivacy){
                binding.ivPrivacyAgree.setImageResource(R.drawable.ic_privacy_checked)
            }else{
                binding.ivPrivacyAgree.setImageResource(R.drawable.ic_privacy_default)
            }
        }


        binding.ivWxLogin.clickWithTrigger {
            if (!isAgreePrivacy){
                ToastUtils.show("请同意隐私协议")
                return@clickWithTrigger
            }
            WXWrapper.instance.login()
        }

    }

    private fun initData(){
//        viewModel.userResult.observe(this){result->
//            result.doSuccess {
//                loadingPop.dismissLoading()
//                it.data?.let {info->
//                    //缓存userinfo
//                    UserPreference.instance.setUserToken(info.token)
//                    UserPreference.instance.setUserInfo(userJsonAdapter.toJson(info))
//                    sendEvent(LoginEvents(true))
//                    finish()
//                    ToastUtils.show("登录成功")
//                }
//
//
//            }
//            result.doFailure {
//                loadingPop.dismissLoading()
//                ToastUtils.show("${it?.message}")
//            }
//        }
//
//        viewModel.codeResult.observe(this){result->
//            result.doSuccess {
//                ToastUtils.show("验证码已发送")
//                binding.cvLoginCountdown.start()
//            }
//            result.doFailure {
//                ToastUtils.show("验证码发送失败${it?.message}")
//            }
//
//        }
      //自己逻辑
    }

    /**
     * 发送验证码
     */
    private fun sendSmsCode(phone:String) {
        GlobalApi.getVerificationCode(phone,object : ApiCallback<BaseResult<Void?>?>{
            override fun onSuccess(result: BaseResult<Void?>?) {
                ToastUtils.show("验证码已发送")
            }


            override fun onFailure(errorMessage: String) {
                ToastUtils.show(errorMessage)
            }

            override fun onFinish() {

            }

        })
    }

    /**
     * 登录手机号
     */
    private fun loginByCode(params: LoginBean){
        GlobalApi.login(params,object : ApiCallback<BaseResult<LoginResultBean?>?>{
            override fun onSuccess(result: BaseResult<LoginResultBean?>?) {
                ToastUtils.show("登录成功")
                MMKVUtils.saveObject(com.hlyj.http.base.tool.lib_hlyj_base.Constants.LoginResultBean, result?.data)
                sendEvent(LoginEvents(true))
                finish()
            }



            override fun onFailure(errorMessage: String) {
                ToastUtils.show(errorMessage)
            }

            override fun onFinish() {

            }

        })
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.cvLoginCountdown.stop()
    }

}